<?php

declare(strict_types=1);

namespace app\sys\controller;

use app\biz\model\BizAccount;
use app\sys\service\SystemMenuService;
use think\admin\Controller;
use think\admin\Exception;
use think\admin\model\SysMerchant;
use think\admin\model\SysRelation;
use think\admin\model\SysRole;
use think\admin\model\SysUser;
use think\admin\service\AdminService;
use think\db\exception\DataNotFoundException;
use think\db\exception\ModelNotFoundException;
use think\exception\DbException;

/**
 * 后台用户接口
 * Class User
 * @package app\sys\controller
 */
class User extends Controller
{
    /**
     * 获取一条后台用户详情
     * @auth true
     * @return void
     */
    public function detail()
    {
        sysoplog('后台用户管理', '后台用户详情获取成功');
        $this->success('操作成功', SysUser::detail($this->request->param('id')));
    }

    /**
     * 添加后台用户
     * @auth true
     * @return void
     */
    public function add()
    {
        sysoplog('后台用户管理', '后台用户新增成功');
        SysUser::mForm('form');
    }

    /**
     * 更新后台用户
     * @auth true
     * @return void
     */
    public function edit()
    {
        sysoplog('后台用户管理', '后台用户更新成功');
        SysUser::mForm('form');
    }

    /**
     * 修改后台用户状态
     * @auth true
     * @return void
     */
    public function state()
    {
        $this->_checkInput();
        sysoplog('后台用户管理', '后台用户状态修改成功');
        SysUser::mSave($this->_vali([
            'status.in:0,1' => '状态值范围异常！',
            'status.require' => '状态值不能为空！',
        ]));
    }

    /**
     * 检查输入变量
     * @return void
     */
    private function _checkInput()
    {
        if (in_array('10000', str2arr(input('id', '')))) {
            $this->error('系统超级账号禁止操作！');
        }
    }

    /**
     * * 获取该用户的所有商户ID
     * @auth true
     * @return void
     */
    public function ownMerchant()
    {
        $merchants = SysRelation::mk()
            ->whereIn('object_id', $this->request->param('id'))
            ->where(['category' => 'SYS_USER_HAS_MERCHANT'])
            ->column('target_id');
        $this->success('获取成功！', $merchants);
    }

    /**
     * 获取该用户的所有租户ID
     * @auth true
     * @return void
     */
    public function ownTenant()
    {
        $tenants = SysRelation::mk()
            ->whereIn('object_id', $this->request->param('id'))
            ->where(['category' => 'SYS_USER_HAS_TENANT'])
            ->column('target_id');
        $this->success('获取成功！', $tenants);
    }

    /**
     * 获取该用户的所有角色ID
     * @auth true
     * @return void
     */
    public function ownRole()
    {
        $roles = SysRelation::mk()
            ->whereIn('object_id', $this->request->param('id'))
            ->where(['category' => 'SYS_USER_HAS_ROLE'])
            ->column('target_id');
        $this->success('获取成功！', $roles);
    }

    /**
     * 获取商户列表
     * @auth true
     * @return void
     * @throws DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws ModelNotFoundException
     */
    public function merchantSelector()
    {
        $query = SysMerchant::mQuery();
        $query->where(['is_deleted' => 0, 'status' => 0]);
        $query->equal('merchant_id');
        $query->like('name,person_name');
        $merchants = $query->order('id ASC')->page(false, false, false);
        $this->success('获取成功！', $merchants['list']);
    }

    /**
     * 后台用户分页列表
     * @auth true
     * @return void
     * @throws DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws ModelNotFoundException
     */
    public function page()
    {
        $query = SysUser::mQuery();
        $query->where(['is_deleted' => 0]);

        // 数据列表搜索过滤
        $query->equal('parent_id,status')->dateBetween('create_time');
        $query->like('name,code');
        $query->append(['full_phone', 'full_email']);
        // 确保 email 或 phone 字段不为空
        $query->where(function($subQuery) {
            $subQuery->whereNotNull('email')->whereOr('phone', 'not null');
        });
        $query->dataScope('created_by');
        $lists = $query->order('id ASC')->page();
    }

    /**
     * 获取角色列表
     * @auth true
     * @return void
     * @throws DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws ModelNotFoundException
     */
    public function roleSelector()
    {
        $query = SysRole::mQuery();
        $query->where(['is_deleted' => 0, 'status' => 0]);
        $query->like('category');
        $roles = $query->order('id ASC')->page(false, false, false);
        $this->success('获取成功！', $roles['list']);
    }


    /**
     * 主管选择器
     * @auth true
     * @return void
     * @throws DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws ModelNotFoundException
     */
    public function userSelector()
    {
        $users = SysUser::mk()
            ->where(['is_deleted' => 0, 'status' => 0])
            ->order('id asc')
            ->field('id,name,account')
            ->select()
            ->toArray();
        sysoplog('账号管理', '主管选择器获取成功');
        $this->success('数据获取成功', $users);
    }

    /**
     * 用户分配租户
     * @auth true
     * @return void
     * @throws \think\db\exception\DbException
     */
    public function grantTenant()
    {
        $id = $this->request->post('id');
        $tenantIdList = $this->request->post('tenantIdList');
        $extJson = $this->request->post('extJson', '');
        if ($id) {//用户ID存在
            if (!empty($tenantIdList)) {//租户列表存在
                if (SysRelation::mk()->where(['object_id' => $id, 'category' => 'SYS_USER_HAS_TENANT'])->findOrEmpty()->save([
                    'object_id' => $id,
                    'target_id' => $tenantIdList[0] ?? null,
                    'category' => 'SYS_USER_HAS_TENANT',
                    'ext_json' => json_encode(['tenantId' => $tenantIdList[0] ?? null, 'userId' => $id, 'adminType' => 'tenantAdmin'], JSON_UNESCAPED_UNICODE)
                ])) {
                    $this->success('已为该用户分配租户');
                } else {
                    $this->error('租户分配失败');
                }
            } else {//用户ID存在，租户ID为空
                if (SysRelation::mk()->where(['object_id' => $id, 'category' => 'SYS_USER_HAS_TENANT'])->delete()) {
                    $this->success('该用户已移除租户信息');
                }
                $this->error('未知错误');
            }
        } else {//用户ID不存在
            $this->error('用户ID不存在，租户分配失败。');
        }
    }

    /**
     * 移到回收站
     * @auth true
     * @return void
     */
    public function delete()
    {
        $this->_checkInput();
        sysoplog('后台用户管理', '后台用户删除成功');
        SysUser::mSave(['is_deleted' => 1]);
    }

    /**
     * 用户分配商户
     * @auth true
     * @return void
     * @throws \think\db\exception\DbException
     */
    public function grantMerchant()
    {
        $id = $this->request->post('id');
        $account = $this->request->post('account');
        $name = $this->request->post('name');
        $phone = $this->request->post('phone');
        $status = $this->request->post('status');
        $merchantIdList = $this->request->post('merchantIdList');
        $extJson = $this->request->post('extJson', '');

        if ($id) {//用户ID存在
            if (!empty($merchantIdList)) {//商户列表存在
                $accountSave = BizAccount::mk()->where(['user_id'=>$id])->findOrEmpty()->save([
                    'merchant_id'=> $extJson[0]['merchantId'] ?? '',
                    'merchant_name'=> $extJson[0]['name'] ?? '',
                    'user_id'=>$id,
                    'account'=>$account,
                    'name'=>$name,
                    'contacts'=>$name,
                    'phone'=>$phone,
                    'status'=>$status,
                    'created_by' => AdminService::getUserId() // 这里不要用平台管理员去分配，应该用租户管理员去分配
                ]);
                $relation = SysRelation::mk()->where(['object_id' => $id, 'category' => 'SYS_USER_HAS_MERCHANT'])->findOrEmpty()->save([
                    'object_id' => $id,
                    'target_id' => $merchantIdList[0] ?? null,
                    'category' => 'SYS_USER_HAS_MERCHANT',
                    'ext_json' => json_encode($extJson, JSON_UNESCAPED_UNICODE)
                ]);

                if ($relation && $accountSave) {
                    $this->success('已为该用户分配商户');
                } else {
                    $this->error('商户分配失败');
                }
            } else {//用户ID存在，租户ID为空
                if (SysRelation::mk()->where(['object_id' => $id, 'category' => 'SYS_USER_HAS_MERCHANT'])->delete()) {
                    $this->success('该用户已移除商户信息');
                }
                $this->error('未知错误');
            }
        } else {//用户ID不存在
            $this->error('用户ID不存在，商户分配失败。');
        }
    }

    /**
     * 用户分配角色
     * @auth true
     * @return void
     * @throws \think\db\exception\DbException
     */
    public function grantRole()
    {
        $id = $this->request->post('id');
        $roleIdList = $this->request->post('roleIdList');
        if ($id) {//用户ID存在
            if (!empty($roleIdList)) {//角色列表存在
                SysRelation::mk()->where(['object_id' => $id, 'category' => 'SYS_USER_HAS_ROLE'])->delete();
                $data = [];
                foreach ($roleIdList as $v) {
                    $data[] = [
                        'object_id' => $id,
                        'target_id' => $v,
                        'category' => 'SYS_USER_HAS_ROLE'
                    ];
                }
                if (SysRelation::mk()->insertAll($data)) {
                    $this->success('角色授权成功');
                }
            } else {//用户ID存在，角色ID为空则删除该用户所有角色
                if (SysRelation::mk()->where(['object_id' => $id, 'category' => 'SYS_USER_HAS_ROLE'])->delete()) {
                    $this->success('角色授权已删除');
                }
            }
        } else {//用户ID不存在
            $this->error('用户ID不存在，角色授权失败。');
        }
    }

    /**
     * 用户资源授权
     * @auth true
     * @return void
     * @throws \think\db\exception\DbException
     */
    public function grantResource()
    {
        $id = $this->request->post('id');
        $grantInfoList = $this->request->post('grantInfoList');
        if ($id) { //用户ID存在
            if (!empty($grantInfoList)) {//菜单、按钮数组存在
                SysRelation::mk()->where(['object_id' => $id, 'category' => 'SYS_USER_HAS_RESOURCE'])->delete();
                $data = [];
                foreach ($grantInfoList as $v) {
                    if (!isset($v['buttonInfo'])) {
                        $v['buttonInfo'] = [];
                    }
                    $data[] = [
                        'object_id' => $id,
                        'target_id' => $v['menuId'],
                        'category' => 'SYS_USER_HAS_RESOURCE',
                        'ext_json' => json_encode($v)
                    ];
                }
                if (SysRelation::mk()->insertAll($data)) {
                    $this->success('资源授权成功');
                }
            } else {//用户ID存在，菜单、按钮数组ID为空则删除该用户所有菜单
                if (SysRelation::mk()->where(['object_id' => $id, 'category' => 'SYS_USER_HAS_RESOURCE'])->delete()) {
                    $this->success('资源授权已删除');
                }
            }
        } else {//用户ID不存在
            $this->error('用户ID不存在，资源授权失败。');
        }
    }

    /**
     * 用户授权权限
     * @auth true
     * @return void
     * @throws \think\db\exception\DbException
     */
    public function grantPermission()
    {
        $id = $this->request->post('id');
        $grantInfoList = $this->request->post('grantInfoList');
        if ($id) { //用户ID存在
            if (!empty($grantInfoList)) {//权限数组存在
                SysRelation::mk()->where(['object_id' => $id, 'category' => 'SYS_USER_HAS_PERMISSION'])->delete();
                $data = [];
                foreach ($grantInfoList as $v) {
                    if (!isset($v['scopeDefineOrgIdList'])) {
                        $v['scopeDefineOrgIdList'] = [];
                    }
                    $data[] = [
                        'object_id' => $id,
                        'target_id' => $v['apiUrl'],
                        'category' => 'SYS_USER_HAS_PERMISSION',
                        'ext_json' => json_encode($v)
                    ];
                }
                if (SysRelation::mk()->insertAll($data)) {
                    $this->success('权限授权成功');
                }
            } else {//用户ID存在，权限数组为空则删除该用户所有权限
                if (SysRelation::mk()->where(['object_id' => $id, 'category' => 'SYS_USER_HAS_PERMISSION'])->delete()) {
                    $this->success('权限授权已删除');
                }else{
                    $this->error('权限不存在，请先选择接口');
                }
            }
        } else {//用户ID不存在
            $this->error('用户ID不存在，权限授权失败。');
        }
    }

    /**
     * 用户已授权的资源
     * @auth true
     * @return void
     */
    public function ownResource()
    {
        $data['id'] = $this->request->param('id');
        $grantInfoList = SysRelation::mk()
            ->whereIn('object_id', $this->request->param('id'))
            ->where(['category' => 'SYS_USER_HAS_RESOURCE'])
            ->column('ext_json');
        $data['grantInfoList'] = [];
        if ($grantInfoList) {
            foreach ($grantInfoList as $v) {
                $data['grantInfoList'][] = json_decode($v, true);
            }
        }
        $this->success('获取成功！', $data);
    }

    /**
     * 用户已授权的权限
     * @auth true
     * @return void
     */
    public function ownPermission()
    {
        $data['id'] = $this->request->param('id');
        $grantInfoList = SysRelation::mk()
            ->whereIn('object_id', $this->request->param('id'))
            ->where(['category' => 'SYS_USER_HAS_PERMISSION'])
            ->column('ext_json');
        $data['grantInfoList'] = [];
        if ($grantInfoList) {
            foreach ($grantInfoList as $v) {
                $data['grantInfoList'][] = json_decode($v, true);
            }
        }
        $this->success('获取成功！', $data);
    }

    /**
     * 重置密码
     * @auth true
     * @return void
     * @throws Exception
     */
    public function resetPassword()
    {
        $data['id'] = intval($this->request->post('id'));
        $data['password'] = md5(sysconfig('OTHER', 'SQM_SYS_DEFAULT_PASSWORD'));
        SysUser::mSave($data);
    }

    /**
     * 添加表单处理
     * @param array $data
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     * @throws DbException
     */
    protected function _form_filter(array &$data)
    {
        $data['latestLoginTime'] = date('Y-m-d h:i:s', time());
    }
}